package cn.yedong.user.service.impl;

import cn.yedong.basic.exception.BusinessException;
import cn.yedong.basic.util.Md5Utils;
import cn.yedong.basic.util.StrUtils;
import cn.yedong.user.domain.Logininfo;
import cn.yedong.user.domain.User;
import cn.yedong.user.mapper.LogininfoMapper;
import cn.yedong.user.mapper.UserMapper;
import cn.yedong.user.service.IUserService;
import cn.yedong.basic.service.impl.BaseServiceImpl;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 添加
     * @param user
     */
    @Transactional
    @Override
    public void add(User user) {
        //密码和盐值
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //先添加logininfo-产生自增id
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//用户
        logininfo.setDisable(true);
        logininfoMapper.add(logininfo);//-产生自增id

        //保存user
        user.setLogininfoId(logininfo.getId());
        super.add(user);
    }

    /**
     * 修改
     * @param user
     */
    @Transactional
    @Override
    public void update(User user) {
        //密码和盐值
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        //获取数据库中user【user的id跟数据库中user对象一致】
        User dbUser = userMapper.loadById(user.getId());
        //更新user的logininfoId
        user.setLogininfoId(dbUser.getLogininfoId());
        //修改user
        super.update(user);

        //获取数据库中logininfo
        Logininfo dbLogininfo = logininfoMapper.loadById(dbUser.getLogininfoId());
        //将user拷贝至dbLogininfo
        BeanUtils.copyProperties(user,dbLogininfo);
        //【注意】：将user拷贝至dbLogininfo时候，dbLogininfo的id会被覆盖成user的id；所以需要设置回本身的id
        dbLogininfo.setId(dbUser.getLogininfoId());
        //修改dbLogininfo
        logininfoMapper.update(dbLogininfo);
    }

    /**
     * 删除
     * @param id
     */
    @Transactional
    @Override
    public void del(Long id) {
        //获取user
        User user = userMapper.loadById(id);
        //根据logininfoId删除logininfo
        logininfoMapper.del(user.getLogininfoId());
        super.del(id);
    }

    /**
     * 批量删除
     * @param ids
     */
    @Transactional
    @Override
    public void patchDel(List<Long> ids) {
        List<Long> logininfoIds = new ArrayList<>();
        for (Long id:ids) {
            User user = userMapper.loadById(id);
            Long logininfoId = user.getLogininfoId();
            logininfoIds.add(logininfoId);
        }
        logininfoMapper.patchDel(logininfoIds);
        super.patchDel(ids);
    }

    /**
     * 手机号码注册
     * @param map
     */
    @Transactional
    @Override
    public void phoneRegister(Map<String, String> map) {
        //从Map集合获取前端参数
        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String password = map.get("password");
        String passwordRepeat = map.get("passwordRepeat");
        //1.空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode)
        ||StringUtils.isEmpty(password) ||StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("后端校验：信息不能为空！");
        }
        //2.密码是否一致
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("后端校验：两次密码不一致！");
        }
        //3.验证码是否过期
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if(obj == null){
            throw new BusinessException("手机验证码已过期！");
        }
        //4.校验手机验证码
        String oldPhoneCode = obj.toString().split(":")[0];
        if(!phoneCode.equals(oldPhoneCode)){
            throw new BusinessException("手机验证码输入错误！");
        }
        //存入数据库
        //1.将一个对象转换成另一个对象
        User user = map2User(map);
        Logininfo logininfo = user2Logininfo(user);
        //2.先添加logininfo，再添加user
        logininfoMapper.add(logininfo);
        //logininfo产生自增id，添加到user表
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    /**
     * 邮箱注册
     * @param map
     */
    @Transactional
    @Override
    public void mailRegister(Map<String, String> map) throws MessagingException {
        //获取参数
        String email = map.get("email");
        String password = map.get("password");
        String passwordRepeat = map.get("passwordRepeat");
        //一：校验
        //空值校验
        if(StringUtils.isEmpty(email) || StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("后端校验：信息不能为空！");
        }
        //重复注册校验
        User dbUser = userMapper.findByEmail(email);
        if(dbUser != null){
            throw new BusinessException("后端校验：不能重复注册！请直接登陆,忘记邮箱密码请联系管理员！");
        }
        //密码有效性校验
        if(!password.equals(passwordRepeat)){
            throw new BusinessException("后端校验：两次密码不一致！");
        }
        //二：存入数据库
        //转换对象
        User user = map2User(map);
        Logininfo logininfo = user2Logininfo(user);
        //先添加logininfo-产生自增id
        logininfoMapper.add(logininfo);
        //再添加user
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
        //三：发送激活邮件——激活成功：更改user状态；更改logininfo状态
        //创建复杂有限对象
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "utf-8");
        messageHelper.setFrom("974431480@qq.com");
        messageHelper.setSubject("【宠物之家】用户注册成功通知！");
        //获取user的id;用于激活时候修改状态
        Long userId = user.getId();
        messageHelper.setText("邮箱是"+email+"的用户您好,恭喜您成为【宠物之家】会员，请<a href='http://localhost:8080/user/register/mailActive/"+userId+"'>点击该链接</a>"+"激活账户！",true);
        messageHelper.setTo(email);
        javaMailSender.send(message);
    }

    /**
     * 邮箱注册用户-激活
     * @param userId
     */
    @Transactional
    @Override
    public void mailActive(Long userId) {
        //思考：如果用户将激活链接地址栏id更改后进行激活？怎么规避？

        User user = userMapper.loadById(userId);
        //修改登陆信息
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        logininfo.setDisable(true);//激活才能用；
        logininfoMapper.update(logininfo);
        //修改用户状态-启用
        user.setState(1);
        userMapper.update(user);
    }

    /**
     * 拷贝对象：将user对象拷贝至logininfo对象
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //根据属性同名原则拷贝对象——将user拷贝至logininfo
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//前台注册：用户

        //email为null-手机注册；phone为null-邮箱注册
        if(user.getEmail() == null){
            logininfo.setDisable(true);//手机注册-默认启动
        }else {
            logininfo.setDisable(false);//邮箱注册-默认禁用
        }
        return logininfo;
    }


    /**
     * 拷贝数据：将map集合拷贝至user对象
     * @param map
     * @return
     */
    private User map2User(Map<String, String> map) {
        User user = new User();
        if(map.get("email") == null){
            //手机注册——email为null
            String phone = map.get("phone");
            user.setUsername(phone);
            user.setPhone(phone);
            user.setState(1);//手机注册-直接设置状态-启动
        }else {
            //邮箱注册——phone为null
            String email = map.get("email");
            user.setUsername(email);
            user.setEmail(email);
            user.setState(0);//邮箱注册-设置状态-禁用——需用邮件激活
        }
        //生成32位随机盐
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(map.get("password") + salt);
        user.setPassword(md5Pwd);
        return user;
    }
}
